<?php
namespace app\api\model;

use think\Model;
/**
 * 手机验证码校验
 */
class PhoneCode extends Model
{
	protected $table = 'phone_codes';
    protected $autoWriteTimestamp = 'timestamp';
    protected $createTime = 'created_at';
    protected $updateTime = 'updated_at';
	const TIME = '10';

    /**
     * [Send 发送验证码]
     * @param [type] $phone [description]
     * @param [type] $code  [description]
     */
	public function Send($phone, $uuid)
	{
		$code = $this->getInvitation();
		$session_id = $uuid;
		$table_se_id = $this->where('session_id',$session_id)->find();//halt($table_se_id);

		if (empty($table_se_id)) {
			self::create(['mobile' =>$phone,'code'=>$code,'session_id'=>$session_id,'mark'=>1]);
		}
		$this->where('session_id',$session_id)->update(['mark'=>'1','code'=>$code]);
		$re = \services\SmsFactory::init('WmSms')->sendCaptcha($phone,$code,self::TIME);
		if ($re) {
			return true;
		}
		return false;
	}
	/**
	 * [CheckPhoneCode 检测验证码]
	 * @param [type] $loc_code [description]
	 * @param [type] $pho_code [description]
	 */
	public function Check($code,$uuid)
	{
		$data = self::get(['code'=>$code,'session_id'=>$uuid]);
		if ($data) {
			if ($data->mark == 1) {
				$this->where('code',$code)->where('session_id',$uuid)->setField('mark',0);
				return true;
			}
		}	
		return false;	
	}
	/**
	 * [getInvitation 生成验证码]
	 * @param  integer $len  [description]
	 * @param  integer $type [description]
	 * @return [type]        [description]
	 */
	private function getInvitation($len = 6, $type = 1)
    {
        switch ($type) {
            case 1:
                $codeSet = '0123456789';
                break;
            case 2:
                $codeSet = 'abcdefhijkmnpqrstuvwxyz';
                break;
            case 3:
                $codeSet = '2345678abcdefhijkmnpqrstuvwxyz';
                break;
            case 4:
                $codeSet = 'abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY';
                break;
            case 5:
                $codeSet = '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY';
                break;

            default:
                $codeSet = '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY';
                break;
        }

        return substr(str_shuffle(str_repeat($codeSet, $len)), 0, $len);
    }

}